package com.example.messagemodule.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.examination.mlib.constants.ARouterConstants;
import com.examination.mlib.constants.AllStringConstants;
import com.examination.mlib.constants.ClickApi;
import com.examination.mlib.constants.KitArouterConstants;
import com.examination.mlib.constants.ProjectConfigure;
import com.examination.mlib.constants.UserInfoConstants;
import com.examination.mlib.manager.LocalNotificatioManager;
import com.examination.mlib.manager.ThreadPoolManager;
import com.example.messagemodule.R;
import com.example.messagemodule.adapter.OldConversationAdapter;
import com.example.messagemodule.entity.ConversationEntity;
import com.example.messagemodule.entity.EventBusMessageEntity;
import com.example.messagemodule.entity.LoginAccountEntity;
import com.example.messagemodule.adapter.ConversationAdapter;
import com.example.messagemodule.entity.MyDoctorListEntity;
import com.example.messagemodule.entity.NotReadMessageCountEntity;
import com.example.messagemodule.entity.OldConversationEntity;
import com.example.messagemodule.utils.MessageUtils;
import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMConversationListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMCursorResult;
import com.hyphenate.chat.EMCustomMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.exceptions.HyphenateException;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.examination.mlib.baseold.ModuleBaseFragment;
import com.examination.mlib.interfaceapi.DrugListBackApi;
import com.examination.mlib.interfaceapi.MessageCallApi;
import com.examination.mlib.interfaceapi.NetWorkCallBack;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.network.https.interceptor.NetWorkUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ActivityManagerUtils;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.DataUtils;
import com.yilijk.base.utils.DevicesUtils;
import com.yilijk.base.utils.LoadingUtils;
import com.yilijk.base.utils.ScreenUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;


import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.FutureTask;

import crossoverone.statuslib.StatusUtil;

import static com.examination.mlib.constants.AllStringConstants.myDoctorList;

/**
 * 消息列表
 * im username user_hospital_117275227127809
 * im password b2a60b20c54e94707e0336db944d3038
 */
@Route(path = ARouterConstants.IM_FRAGMENT)
public class ConversationListFragment extends ModuleBaseFragment implements EMMessageListener, EMConnectionListener, EMConversationListener {


    private LinearLayout healthMsgLayout;
    private ImageView healthMsgNew;
    private TextView healthMsgTime;
    private TextView healthMsgContent;
    private LinearLayout conversationNoList;

    private TextView titlebarTitle;
    private RecyclerView conversationList;
    private ArrayList<ConversationEntity.DataBean> patientImMsgListBeans = new ArrayList<>();
    private ArrayList<OldConversationEntity.DataBean.PatientImMsgListBean> oldPatientImMsgListBeans = new ArrayList<OldConversationEntity.DataBean.PatientImMsgListBean>();
    private ConversationAdapter conversationAdapter;
    private OldConversationAdapter oldConversationAdapter;
    private SmartRefreshLayout messageSmart;
    private Handler handler = new Handler() {
    };

    @Override
    public int bondLayout() {
        return R.layout.fragment_conversation_list;
    }

    @Override
    public void initView() {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("name", "消息列表载入");
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        ClickUtils.sendEvent("pages_messages_load", getContext(), jsonObject);

        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.color_F4F4F4, android.R.color.black);//全局设置主题颜色
                ClassicsHeader classicsHeader = new ClassicsHeader(context);
                return classicsHeader;//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
        //设置标题
        titlebarTitle = (TextView) findViewById(R.id.titlebar_title);
        titlebarTitle.setText("消息");
        int statusH = StatusUtil.getStatusBarHeight(getContext());
        if (statusH <= 0) {
            statusH = ScreenUtils.dip2px(getContext(), 26);
        }
        titlebarTitle.setPadding(0, statusH + ScreenUtils.dip2px(getContext(), 20), 0, ScreenUtils.dip2px(getContext(), 20));

        messageSmart = (SmartRefreshLayout) findViewById(R.id.message_smart);

//        conversationSystemContent = (TextView) findViewById(R.id.conversation_system_content);
//        conversationSystemUnread = (TextView) findViewById(R.id.conversation_system_unread);
//        systemItem = (RelativeLayout) findViewById(R.id.system_item);
        healthMsgLayout = (LinearLayout) findViewById(R.id.health_msg_layout);
        healthMsgNew = (ImageView) findViewById(R.id.health_msg_new);
        healthMsgTime = (TextView) findViewById(R.id.health_msg_time);
        healthMsgContent = (TextView) findViewById(R.id.health_msg_content);

        conversationNoList = (LinearLayout) findViewById(R.id.conversation_no_list);

        //设置 Footer 为 球脉冲 样式
        messageSmart.setRefreshFooter(new BallPulseFooter(getContext()).setSpinnerStyle(SpinnerStyle.Scale));
        //列表初始化
        conversationAdapter = new ConversationAdapter(patientImMsgListBeans);
        oldConversationAdapter = new OldConversationAdapter(oldPatientImMsgListBeans);
        conversationList = (RecyclerView) findViewById(R.id.conversation_list);
        conversationList.setLayoutManager(new LinearLayoutManager(getContext()));
        if (ProjectConfigure.Open.isOpenGroup) {
            conversationList.setAdapter(conversationAdapter);
            conversationAdapter.notifyDataSetChanged();
        } else {
            conversationList.setAdapter(oldConversationAdapter);
            oldConversationAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void initData() {
    }

    @Override
    public void initEvent() {
        ClickUtils.setFastOnClickListener(findViewById(R.id.conversation_no_list_bt), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClickUtils.sendEvent(ClickApi.Message.click_fastAsk, getActivity(), "立即咨询医生");
                RequestParams jsonObject = new RequestParams();
                jsonObject.put("pageId", 1);
                jsonObject.put("size", 2);
                HttpUtils.get(myDoctorList, jsonObject, new HttpCallBack<MyDoctorListEntity>() {
                    @Override
                    public void onSuccess(MyDoctorListEntity entity, int code) {
                        if (code == 200 && entity != null && "200".equals(entity.getStatus())) {
                            if (entity.getData() != null && entity.getData().getList() != null && entity.getData().getList().size() == 1) {
                                Bundle bundle = new Bundle();
                                bundle.putString("doctorId", entity.getData().getList().get(0).getDoctorId());
                                bundle.putInt("selectIndex", 1);
                                MessageUtils.push(getContext(), KitArouterConstants.IM_DOCTORBUNDLE, KitArouterConstants.Message.DoctorStudio, bundle);
                            } else {

                                DrugListBackApi drugListBackApi = (DrugListBackApi) ARouter.getInstance().build(ARouterConstants.DrugListModuleImpl).navigation();
                                drugListBackApi.changeHomeFragment(getActivity());
                            }
                        } else {
                            DrugListBackApi drugListBackApi = (DrugListBackApi) ARouter.getInstance().build(ARouterConstants.DrugListModuleImpl).navigation();
                            drugListBackApi.changeHomeFragment(getActivity());
                        }
                    }

                    @Override
                    public void onFailure(String s, int i) {
                        DrugListBackApi drugListBackApi = (DrugListBackApi) ARouter.getInstance().build(ARouterConstants.DrugListModuleImpl).navigation();
                        drugListBackApi.changeHomeFragment(getActivity());
                    }
                });
            }
        });


        //系统消息点击
        ClickUtils.setFastOnClickListener(healthMsgLayout, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClickUtils.sendEvent(ClickApi.Message.click_systemmsg, getActivity(), "系统消息点击");
                Bundle bundle = new Bundle();
                String account_id = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.account_id, "");
                bundle.putInt("sessUid", account_id != null && account_id.length() > 0 ? Integer.valueOf(account_id) : -1);
                MessageUtils.push(getActivity(), KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.HealthConsult, bundle);
            }
        });

        /**
         *
         * TODO 消息列表点击
         */
        ClickUtils.setAdapterItemFastOnClickListener(conversationAdapter, new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ClickUtils.sendEvent(ClickApi.Message.click_chat, getActivity(), "聊天点击" + position);
                if (!TextUtils.isEmpty(patientImMsgListBeans.get(position).getImTeamId())) {
                    if (patientImMsgListBeans.get(position).getChargesListId() != 0) {
                        ARouter.getInstance().build(ARouterConstants.ConversationActivity)
                                .withBoolean("isInquiryRecord", false)
                                .withInt("chatTypeStatus", 1)
                                .withString("externalOrderNo", patientImMsgListBeans.get(position).getChargesListId() + "")
                                .navigation();
                    }
                } else {
                    if (patientImMsgListBeans == null) {
                        //TODO patientImMsgListBeans is null
                    } else if (patientImMsgListBeans.size() == 0) {
                        //TODO patientImMsgListBeans size is 0
                    } else if (position > patientImMsgListBeans.size()) {
                        //TODO click position is error
                    } else if (patientImMsgListBeans.get(position) == null) {
                        //TODO click patientImMsgListBeans position is null
                    } else if (TextUtils.isEmpty(patientImMsgListBeans.get(position).getDoctorPassportId())) {

                    } else if (patientImMsgListBeans.get(position).getChargesListId() == 0) {
                        //TODO click patientImMsgListBeans ChargesListId is 0
                    } else {
                        ARouter.getInstance()
                                .build(ARouterConstants.ConversationActivity)
                                .withLong("doctorPassportId", Long.parseLong(patientImMsgListBeans.get(position).getDoctorPassportId()))
                                .withBoolean("isInquiryRecord", false)
                                .withInt("chatTypeStatus", 0)
                                .navigation();
                    }
                }
            }
        });

        /**
         *
         * TODO 消息列表点击
         */
        ClickUtils.setAdapterItemFastOnClickListener(oldConversationAdapter, new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ClickUtils.sendEvent(ClickApi.Message.click_chat, getActivity(), "聊天点击" + position);
                if (oldPatientImMsgListBeans == null) {
                    //TODO patientImMsgListBeans is null
                } else if (oldPatientImMsgListBeans.size() == 0) {
                    //TODO patientImMsgListBeans size is 0
                } else if (position > oldPatientImMsgListBeans.size()) {
                    //TODO click position is error
                } else if (oldPatientImMsgListBeans.get(position) == null) {
                    //TODO click patientImMsgListBeans position is null
                } else if (oldPatientImMsgListBeans.get(position).getDoctorPassportId() == 0) {
                    //TODO click patientImMsgListBeans doctorpassportId is 0
                } else if (oldPatientImMsgListBeans.get(position).getChargesListId() == 0) {
                    //TODO click patientImMsgListBeans ChargesListId is 0
                } else {
                    ARouter.getInstance()
                            .build(ARouterConstants.ConversationActivity)
                            .withLong("doctorPassportId", oldPatientImMsgListBeans.get(position).getDoctorPassportId())
                            .withBoolean("isInquiryRecord", false)
                            .withInt("chatTypeStatus", 0)
                            .navigation();
//
//                    Intent intent = new Intent(getActivity(), ConversationActivity.class);
//                    intent.putExtra("doctorPassportId", patientImMsgListBeans.get(position).getDoctorPassportId());
//                    intent.putExtra("isInquiryRecord",false);
//                    intent.putExtra("chatTypeStatus",0);
//                    startActivity(intent, ActivityOptions.makeSceneTransitionAnimation((Activity) view.getContext(),view,"conversationNormal").toBundle());
                }
            }
        });


        /**
         * TODO 上拉刷新下拉加载
         */
        messageSmart.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (hasNextPage) {
                    pageIndex++;
                    if (ProjectConfigure.Open.isOpenGroup) {
                        getConversationList();
                    } else {
                        getOldConversationList();
                    }
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageIndex = 1;
                pageSize = 10;
                if (ProjectConfigure.Open.isOpenGroup) {
                    getConversationList();
                } else {
                    getOldConversationList();
                }
            }
        });
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EMClient.getInstance().chatManager().addMessageListener(this);
        EMClient.getInstance().chatManager().addConversationListener(this);
        EMClient.getInstance().addConnectionListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        ClickUtils.sendEvent(ClickApi.Message.page_show, getContext(), "消息载入");
        LoadingUtils.getLoadingUtils(getActivity()).showLoading();
        String imAccount = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.imAccount, null);
        String imPassword = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.imPassword, null);
        imLogin(imAccount, imPassword);

        if (ProjectConfigure.Open.isOpenGroup) {
            getConversationList();
        } else {
            getOldConversationList();
        }
        getHealthConsultInfo();
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initData();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatManager().removeMessageListener(this);
        EMClient.getInstance().chatManager().removeConversationListener(this);
        EMClient.getInstance().removeConnectionListener(this);
    }

    /**
     * im普通消息接收
     */
    @Override
    public void onMessageReceived(List<EMMessage> messages) {
        //TODO 首页新消息弹窗的广播

        EMMessage emMessage = messages.get(0);
        if (emMessage.getChatType() == EMMessage.ChatType.Chat){
            Intent intent = new Intent(AllStringConstants.BroadcastReceiver);
            intent.putExtra(AllStringConstants.showPop, true);
            //向广播接收器传递数据
            getActivity().sendBroadcast(intent);      //发送广播
        }
        String from = emMessage.getFrom();
        ALog.e(messages.size()+"");
        if (isExistMsgList(emMessage.getFrom())) {
            emMessageJson(emMessage);
        } else {
            getConversationList();
        }
        for (int i = 0; i < messages.size(); i++) {
            String s = MessageUtils.emMessageJson(messages.get(i), false);
            MessageCallApi messageCallApi = (MessageCallApi) ARouter.getInstance().build(ARouterConstants.MessageModuleImpl).navigation();
            messageCallApi.Android2RnBroadcast(getContext(), "ReceiveOrdinaryChatMessage", s);
        }

    }

    /**
     * im cmd穿透消息接收
     */
    @Override
    public void onCmdMessageReceived(List<EMMessage> messages) {
        EMMessage emMessage = messages.get(0);
        String from = emMessage.getFrom();
        try {
            if (isExistMsgList(emMessage.getFrom())) {
                EMCursorResult<EMMessage> emMessageEMCursorResult = EMClient.getInstance().chatManager().fetchHistoryMessages(from, EMConversation.EMConversationType.Chat, 2, null);
                EMMessage emMessageFromServer = emMessageEMCursorResult.getData().get(0);
                emMessageJson(emMessageFromServer);
            } else {
                getConversationList();
            }
        } catch (HyphenateException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < messages.size(); i++) {
            try {
                EMCursorResult<EMMessage> emMessageEMCursorResult = EMClient.getInstance().chatManager().fetchHistoryMessages(from, EMConversation.EMConversationType.Chat, 2, null);
                EMMessage emMessage1 = emMessageEMCursorResult.getData().get(0);
                String s1 = MessageUtils.emMessageJson(emMessage1, false);
                MessageCallApi messageCallApi = (MessageCallApi) ARouter.getInstance().build(ARouterConstants.MessageModuleImpl).navigation();
                messageCallApi.Android2RnBroadcast(getContext(), "ReceiveOrdinaryChatMessage", s1);
            } catch (HyphenateException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void onMessageRead(List<EMMessage> messages) {

    }

    @Override
    public void onMessageDelivered(List<EMMessage> messages) {

    }

    /**
     * im 消息撤回
     */
    @Override
    public void onMessageRecalled(List<EMMessage> messages) {
        EventBus.getDefault().post(new EventBusMessageEntity("recalled", messages));
        EMMessage emMessage = messages.get(0);
        EMMessage RecallMessage = EMMessage.createTxtSendMessage("[对方撤回了一条消息]", emMessage.getFrom());
        RecallMessage.setFrom(emMessage.getFrom());
        emMessageJson(RecallMessage);
    }

    /**
     * im 消息状态改变
     */
    @Override
    public void onMessageChanged(EMMessage message, Object change) {

    }

    /**
     * 账号登录状态连接
     */
    @Override
    public void onConnected() {

    }

    /**
     * 账号登录状态断开连接
     */
    @Override
    public void onDisconnected(int errorCode) {
        if (errorCode == EMError.USER_REMOVED) {
            //用户被删
            ALog.d("EMConnectionListener", "用户被删");
        } else if (errorCode == EMError.USER_LOGIN_ANOTHER_DEVICE) {
            //账户在另外一台设备登录
            ALog.d("EMConnectionListener", "账户在另外一台设备登录");
        } else if (errorCode == EMError.SERVER_SERVICE_RESTRICTED) {
            //IM功能限制
            ALog.d("EMConnectionListener", "IM功能限制");
        } else if (errorCode == EMError.USER_KICKED_BY_CHANGE_PASSWORD) {
            //用户修改密码
            ALog.d("EMConnectionListener", "用户修改密码");
        } else if (errorCode == EMError.USER_KICKED_BY_OTHER_DEVICE) {
            //用户被其他设备踢掉
            ALog.d("EMConnectionListener", "用户被其他设备踢掉");
        }
        String imAccount = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.imAccount, null);
        String imPassword = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.imPassword, null);
        if (imAccount != null && imPassword != null) {
            imLogin(imAccount, imPassword);
        }
    }

    @Override
    public void onCoversationUpdate() {

    }

    @Override
    public void onConversationRead(String from, String to) {

    }

    private void getHealthConsultInfo() {
        RequestParams jsonObject = new RequestParams();
        jsonObject.put("types", "4");

        HttpUtils.get(AllStringConstants.MessageUrl.NotReadMessageCount, jsonObject, new HttpCallBack<NotReadMessageCountEntity>() {
            @Override
            public void onSuccess(NotReadMessageCountEntity notReadMessageCountEntity, int i) {
                if (notReadMessageCountEntity.getCode() == 200 && notReadMessageCountEntity.getData() != null) {
                    List<NotReadMessageCountEntity.DataBean> data = notReadMessageCountEntity.getData();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (data.get(0) != null && data.get(0).getMessage() != null) {
                                if (data.get(0).getMessage().getTitle() != null &&
                                        !TextUtils.isEmpty(data.get(0).getMessage().getTitle()) &&
                                        !data.get(0).getMessage().getTitle().equals("") &&
                                        !data.get(0).getMessage().getTitle().equals("null")) {
                                    healthMsgContent.setText(data.get(0).getMessage().getTitle());
                                } else {
                                    healthMsgContent.setText("暂无消息");
                                }
                                if (data.get(0).getCount() != 0) {
                                    healthMsgNew.setVisibility(View.VISIBLE);
                                } else {
                                    healthMsgNew.setVisibility(View.GONE);
                                }


                                if (data.get(0).getMessage().getPushTime() != 0) {
                                    String s = DataUtils.long2string(data.get(0).getMessage().getPushTime(), "yyyy-MM-dd");
                                    healthMsgTime.setText(s);
                                }

                            } else {
                                healthMsgContent.setText("暂无消息");
                                healthMsgNew.setVisibility(View.GONE);
                            }


                        }
                    });
                }
            }

            @Override
            public void onFailure(String s, int i) {

            }
        });
    }


    /**
     * 解析消息
     */
    public void emMessageJson(EMMessage emmessage) {
        EMMessage.Type type = emmessage.getType();
        EMMessage.ChatType chatType = emmessage.getChatType();
        String content = "";
        int msgType = 0;
        String event = "";
        if (type == EMMessage.Type.TXT) {
            EMTextMessageBody body = (EMTextMessageBody) emmessage.getBody();
            if (body != null && body.getMessage() != null) {
                content = body.getMessage();
                msgType = 0;
            }
        } else if (type == EMMessage.Type.IMAGE) {
            content = "[图片消息]";
            msgType = 1;
        } else if (type == EMMessage.Type.VOICE) {
            content = "[语音消息]";
            msgType = 2;
        } else if (type == EMMessage.Type.VIDEO) {
            content = "[视频消息]";
            msgType = 3;
        } else if (type == EMMessage.Type.FILE) {
            content = "[文件消息]";
            msgType = 6;
        } else if (type == EMMessage.Type.CUSTOM) {
            msgType = 7;
            EMCustomMessageBody body = (EMCustomMessageBody) emmessage.getBody();
            if (body != null) {
                event = body.event();
            }
        }

        String notificationTitle = "问诊消息";
        int doctorId = 0;
        String doctorpassportId = "";
        if (ProjectConfigure.Open.isOpenGroup) {
            for (int i = 0; i < patientImMsgListBeans.size(); i++) {
                if (patientImMsgListBeans.get(i).getDoctorImAccount() != null && patientImMsgListBeans.get(i).getDoctorImAccount().equals(emmessage.getFrom())) {
                    if (patientImMsgListBeans.get(i).getImRecordHbaseDTO() != null) {
                        patientImMsgListBeans.get(i).getImRecordHbaseDTO().setMsgType(msgType);
                        patientImMsgListBeans.get(i).getImRecordHbaseDTO().setContent(content);
                        patientImMsgListBeans.get(i).getImRecordHbaseDTO().setCustomEvent(event);
                    } else {
                        ConversationEntity.DataBean.ImRecordHbaseDTOBean imRecordHbaseDTOBean = new ConversationEntity.DataBean.ImRecordHbaseDTOBean();
                        imRecordHbaseDTOBean.setMsgType(msgType);
                        imRecordHbaseDTOBean.setContent(content);
                        imRecordHbaseDTOBean.setCustomEvent(event);
                        patientImMsgListBeans.get(i).setImRecordHbaseDTO(imRecordHbaseDTOBean);
                    }
                    notificationTitle = patientImMsgListBeans.get(i).getDoctorName();
                    doctorId = patientImMsgListBeans.get(i).getChargesListId();
                    doctorpassportId = patientImMsgListBeans.get(i).getDoctorPassportId();
                }
            }
            refreshConversationList();
        } else {
            for (int i = 0; i < oldPatientImMsgListBeans.size(); i++) {
                if (oldPatientImMsgListBeans.get(i).getDoctorImAccount() != null && oldPatientImMsgListBeans.get(i).getDoctorImAccount().equals(emmessage.getFrom())) {
                    if (oldPatientImMsgListBeans.get(i).getImRecordHbaseDTO() != null) {
                        oldPatientImMsgListBeans.get(i).getImRecordHbaseDTO().setMsgType(msgType);
                        oldPatientImMsgListBeans.get(i).getImRecordHbaseDTO().setContent(content);
                        oldPatientImMsgListBeans.get(i).getImRecordHbaseDTO().setCustomEvent(event);
                    } else {
                        OldConversationEntity.DataBean.PatientImMsgListBean.ImRecordHbaseDTOBean imRecordHbaseDTOBean = new OldConversationEntity.DataBean.PatientImMsgListBean.ImRecordHbaseDTOBean();
                        imRecordHbaseDTOBean.setMsgType(msgType);
                        imRecordHbaseDTOBean.setContent(content);
                        imRecordHbaseDTOBean.setCustomEvent(event);
                        oldPatientImMsgListBeans.get(i).setImRecordHbaseDTO(imRecordHbaseDTOBean);
                    }
                }
            }
            refreshOldConversationList();
        }

        if (ProjectConfigure.Open.isOpenNotification){
            String finalContent = content;
            String finalNotificationTitle = notificationTitle;
            int finalDoctorId = doctorId;
            String finalDoctorpassportId = doctorpassportId;
            if (ActivityManagerUtils.getLastestActivity() instanceof ConversationActivity) {
                ConversationActivity ca = (ConversationActivity) ActivityManagerUtils.getLastestActivity();
                int chargesListId = 0;
                if (chatType == EMMessage.ChatType.Chat) {
                    chargesListId = ca.entryData.getImChargesList().getChargesListId();
                } else {
                    chargesListId = ca.entryGroupData.getImTeamChargesList().getChargesListId();
                }
                if (chargesListId == doctorId) {
                    return;
                }
            }
            Thread thread = new Thread() {
                @Override
                public void run() {
                    super.run();
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("doctorPassportId", finalDoctorpassportId);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    LocalNotificatioManager.getInstance(getActivity())
                            .NotificationStyle(finalNotificationTitle, finalContent)
                            .NotificationIntent(getContext(), ConversationActivity.class, jsonObject.toString())
                            .NotificationIM(getContext(), finalDoctorId);
                }
            };
            ThreadPoolManager.getInstance().execute(new FutureTask<Object>(thread, null), null);
        }

    }

    /**
     * 判断当前用户是否存在列表
     */
    boolean isExistMsgList(String from) {
        if (ProjectConfigure.Open.isOpenGroup) {
            boolean isExist = false;
            for (int i = 0; i < patientImMsgListBeans.size(); i++) {
                if (patientImMsgListBeans.get(i).getDoctorImAccount() != null && patientImMsgListBeans.get(i).getDoctorImAccount().equals(from)) {
                    isExist = true;
                    break;
                }
            }
            return isExist;
        } else {
            boolean isExist = false;
            for (int i = 0; i < oldPatientImMsgListBeans.size(); i++) {
                if (oldPatientImMsgListBeans.get(i).getDoctorImAccount() != null && oldPatientImMsgListBeans.get(i).getDoctorImAccount().equals(from)) {
                    isExist = true;
                    break;
                }
            }
            return isExist;
        }
    }

    /**
     * 环信登录
     *
     * @param imAccount
     * @param imPassword
     */
    private void imLogin(String imAccount, String imPassword) {
        MessageUtils.imLogin(imAccount, imPassword, new EMCallBack() {
            @Override
            public void onSuccess() {
                dismissLoading();
                ALog.d("环信登录成功", "im login success");
            }

            @Override
            public void onError(int code, String error) {
                if (code == 200) {
                    getConversationList();
                } else {
                    if (ProjectConfigure.Open.isOpenGroup) {
                        refreshConversationList();
                    } else {
                        refreshOldConversationList();
                    }
                }
                ALog.d("环信登录失败", error + code);
            }

            @Override
            public void onProgress(int progress, String status) {
                ALog.d("环信登录中", status + progress);
            }
        });
    }

    @UiThread
    void dismissLoading() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
            }
        });
    }


    /**
     * 获取会话列表
     */
    int pageIndex = 1;
    int pageSize = 1000;
    boolean hasNextPage = true;

    private void getOldConversationList() {
        RequestParams jsonObject = new RequestParams();
        jsonObject.put("pageIndex", pageIndex);
        jsonObject.put("pageSize", pageSize);
        HttpUtils.get(AllStringConstants.queryPatientMsgList, jsonObject, new HttpCallBack<OldConversationEntity>() {
            @Override
            public void onSuccess(OldConversationEntity oldConversationEntity, int i) {
                if (oldConversationEntity.isResult()) {
                    if (oldConversationEntity.getData() == null) {
                        //TODO conversationEntity.getData() is null
                        ALog.i(this.getClass().getName(), "oldPatientImMsgListBeans.getData() is null");
                    } else {
                        hasNextPage = oldConversationEntity.getData().isHasNextPage();
                        if (oldPatientImMsgListBeans == null) {
                            //TODO oldPatientImMsgListBeans is null
                            ALog.i(this.getClass().getName(), "oldPatientImMsgListBeans.getData() is null");
                        } else if (oldConversationEntity.getData().getPatientImMsgList() == null) {
                            ALog.i(this.getClass().getName(), "oldPatientImMsgListBeans.getData().getPatientImMsgList() is null");
                        } else {
                            oldPatientImMsgListBeans.clear();
                            oldPatientImMsgListBeans.addAll(oldConversationEntity.getData().getPatientImMsgList());
                            refreshOldConversationList();
                        }
                    }

                } else {
                    Toast.makeText(getContext(), "" + oldConversationEntity.getMsg(), Toast.LENGTH_SHORT).show();
                }
                LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
            }
        });

    }

    private void getConversationList() {
        RequestParams jsonObject = new RequestParams();
        jsonObject.put("pageIndex", pageIndex);
        jsonObject.put("pageSize", pageSize);
        HttpUtils.get(AllStringConstants.queryPatientMsgListNew, jsonObject, new HttpCallBack<ConversationEntity>() {
            @Override
            public void onSuccess(ConversationEntity conversationEntity, int i) {
                if (conversationEntity.isResult()) {
                    if (conversationEntity.getData() == null) {
                        //TODO conversationEntity.getData() is null
                        ALog.i(this.getClass().getName(), "conversationEntity.getData() is null");
                    } else {
//                            hasNextPage = conversationEntity.getData().isHasNextPage();
                        if (patientImMsgListBeans == null) {
                            //TODO patientImMsgListBeans is null
                            ALog.i(this.getClass().getName(), "conversationEntity.getData() is null");
                        } else if (conversationEntity.getData() == null) {
                            ALog.i(this.getClass().getName(), "conversationEntity.getData().getPatientImMsgList() is null");
                        } else {
                            patientImMsgListBeans.clear();
                            patientImMsgListBeans.addAll(conversationEntity.getData());
                            refreshConversationList();
                        }
                    }

                } else {
                    Toast.makeText(getContext(), "" + conversationEntity.getMsg(), Toast.LENGTH_SHORT).show();
                }
                LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
            }
        });
    }

    /**
     * 刷新列表
     */
    private void refreshConversationList() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (patientImMsgListBeans.size() <= 0 || patientImMsgListBeans == null) {
                    conversationNoList.setVisibility(View.VISIBLE);
                    conversationList.setVisibility(View.GONE);
                } else {
                    conversationNoList.setVisibility(View.GONE);
                    conversationList.setVisibility(View.VISIBLE);
                }
                messageSmart.setEnableLoadMore(hasNextPage);
//                Collections.sort(patientImMsgListBeans);
                conversationAdapter.notifyDataSetChanged();
                messageSmart.finishRefresh();
                messageSmart.finishLoadMore();
                LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
            }
        });
    }

    /**
     * 刷新列表
     */
    private void refreshOldConversationList() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (oldPatientImMsgListBeans.size() <= 0 || oldPatientImMsgListBeans == null) {
                    conversationNoList.setVisibility(View.VISIBLE);
                    conversationList.setVisibility(View.GONE);
                } else {
                    conversationNoList.setVisibility(View.GONE);
                    conversationList.setVisibility(View.VISIBLE);
                }
                messageSmart.setEnableLoadMore(hasNextPage);
//                Collections.sort(patientImMsgListBeans);
                oldConversationAdapter.notifyDataSetChanged();
                messageSmart.finishRefresh();
                messageSmart.finishLoadMore();
                LoadingUtils.getLoadingUtils(getActivity()).dismissLoading();
            }
        });

    }

}